<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\extend\tencent;

/*
	腾讯短信接口插件
	调用方法：
	// $Sms=new \app\extend\tencent\Sms;
	// $data[0]=mt_rand(1000,9999);
	// echo $Sms->SendSms('13477191977',$data,'330371');	
	// echo $Sms->SendVoiceSms('13477191977','4564',336953);
*/
use \app\base\Common;

class Sms extends Common
{
	private $AppID="";
	private $AppKey="";
	private $sign="";
	protected function _initialize()
	{
    	//执行父类的构造方法
    	parent::_initialize();
		$this->AppID=$this->Config['tencent_sms_appid'];
		$this->AppKey=$this->Config['tencent_sms_key'];
		$this->sign=$this->Config['tencent_sms_sign'];
	}
	//发送短信
	public function SendSms($mobile,$params,$tpl_id)
	{
		$random=mt_rand(100000,999999);
		$URL='https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid='.$this->AppID.'&random='.$random;
		$time=time();
		$string='appkey='.$this->AppKey.'&random='.$random.'&time='.$time.'&mobile='.$mobile;
		$sign=hash("sha256",$string);
		$data=array("ext"=>"","extend"=> "","params"=> $params,"sig"=>$sign,"sign"=>$this->sign,"tel"=>array("mobile"=>$mobile,'nationcode'=>86),"time"=>$time,"tpl_id"=>$tpl_id);
       	$aContext = array('http' => array('method' => 'POST', 'header'  => 'Content-type: application/json', 'content' => json_encode($data) ));  
       	$cxContext  = stream_context_create($aContext);  
       	$d_json = @file_get_contents($URL,false,$cxContext);  
		$d = json_decode($d_json,true);
		WLog('tencent_sms_log',$d_json);
		if($d['errmsg']=='OK'){
			return $d;
		}else{
			return false;
		}
	}
	//发送模板语音短信
	public function SendVoiceSms($mobile,$params,$tpl_id)
	{
		$random=mt_rand(100000,999999);
		$URL='https://cloud.tim.qq.com/v5/tlsvoicesvr/sendtvoice?sdkappid='.$this->AppID.'&random='.$random;
		$time=time();
		$string='appkey='.$this->AppKey.'&random='.$random.'&time='.$time.'&mobile='.$mobile;
		$sign=hash("sha256",$string);
		$json='{
				"tpl_id": '.$tpl_id.',
				"params": [ "'.$params.'" ],
				"playtimes":2,
				"sig": "'.$sign.'",
				"tel": {
					"mobile": "'.$mobile.'",
					"nationcode": "86"
				},
				"time": '.$time.',
				"ext": ""
			}';
       	$aContext = array('http' => array('method' => 'POST', 'header'  => 'Content-type: application/json', 'content' => $json));  
       	$cxContext  = stream_context_create($aContext);  
       	$d_json = @file_get_contents($URL,false,$cxContext);  
		$d = json_decode($d_json,true);
		WLog('tencent_voice_sms_log',$d_json);
		if($d['errmsg']=='OK'){
			return $d;
		}else{
			return false;
		}
	}
}
?>